<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="出院日期" prop="dischargeDate">
        <el-date-picker clearable
                        v-model="queryParams.dischargeDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择出院日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="出院诊断" prop="dischargeDiagnosis">
        <el-input
            v-model="queryParams.dischargeDiagnosis"
            placeholder="请输入出院诊断"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="出院医嘱" prop="dischargeAdvice">
        <el-input
            v-model="queryParams.dischargeAdvice"
            placeholder="请输入出院医嘱"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出院情况" prop="dischargeCondition">
        <el-input
            v-model="queryParams.dischargeCondition"
            placeholder="请输入出院情况"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['nurse:chuyuan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['nurse:chuyuan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['nurse:chuyuan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['nurse:chuyuan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chuyuanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者姓名" align="center">
        <template #default="scope">
          <span>{{ getPatientName(scope.row.patientId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出院日期" align="center" prop="dischargeDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.dischargeDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最新住院日期" align="center" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.latestAdmissionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出院诊断" align="center" prop="dischargeDiagnosis" />
      <el-table-column label="出院医嘱" align="center" prop="dischargeAdvice" />
      <el-table-column label="出院情况" align="center" prop="dischargeCondition" />
      <el-table-column label="医生姓名" align="center">
        <template #default="scope">
          <span>{{ getEmployeeName(scope.row.doctorId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="护士姓名" align="center">
        <template #default="scope">
          <span>{{ getEmployeeName(scope.row.nurseId) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nurse:chuyuan:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nurse:chuyuan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改出院记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="chuyuanRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="patientId">
          <el-select
              v-model="form.patientId"
              placeholder="请选择患者姓名"
              clearable
              filterable
              @change="handlePatientChange"
          >
            <el-option
                v-for="patient in patientList"
                :key="patient.patientId"
                :label="patient.realName"
                :value="patient.patientId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="出院日期" prop="dischargeDate">
          <el-date-picker clearable
                          v-model="form.dischargeDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择出院日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出院诊断" prop="dischargeDiagnosis">
          <el-input
              v-model="form.dischargeDiagnosis"
              placeholder="请输入出院诊断"
              type="textarea"
          />
          <el-button
              type="text"
              @click="applyDiagnosisTemplate"
              style="margin-top: 5px;"
          >使用模板</el-button>
        </el-form-item>

        <el-form-item label="出院情况" prop="dischargeCondition">
          <el-input
              v-model="form.dischargeCondition"
              placeholder="请输入出院情况"
              type="textarea"
          />
          <el-button
              type="text"
              @click="applyConditionTemplate"
              style="margin-top: 5px;"
          >使用模板</el-button>
        </el-form-item>

        <el-form-item label="出院医嘱" prop="dischargeAdvice">
          <el-input
              v-model="form.dischargeAdvice"
              placeholder="请输入出院医嘱"
              type="textarea"
          />
          <el-button
              type="text"
              @click="applyAdviceTemplate"
              style="margin-top: 5px;"
          >使用模板</el-button>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Chuyuan">
import {listChuyuan, getChuyuan, delChuyuan, addChuyuan, updateChuyuan} from "@/api/nurse/chuyuan";
import {getMEmoployee, listBeinhospital2, listjiuzhen} from "@/api/nurse/beinhospital.js";
import {parseTime} from "../../../utils/ruoyi.js";
import {listBed, updateBed} from "@/api/nurse/bed.js";

const {proxy} = getCurrentInstance();

const chuyuanList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const patientList = ref([]) // 新增患者列表

function applyDiagnosisTemplate() {
  form.value.dischargeDiagnosis = "患者病情稳定，症状缓解，符合出院标准。";
}

function applyConditionTemplate() {
  form.value.dischargeCondition = "患者一般情况良好，生命体征平稳，无不适。";
}

function applyAdviceTemplate() {
  form.value.dischargeAdvice = "注意休息，保持伤口清洁，按时服药，定期复查。";
}

function getLatestHospitalRecord(patientId) {
  return listBeinhospital2({patientId}).then(response => {
    if (response && response.length > 0) {
      // 找到最近的住院记录
      const latestRecord = response.reduce((latest, current) => {
        return new Date(current.admissionTime) > new Date(latest.admissionTime) ? current : latest;
      });
      return latestRecord;
    } else {
      throw new Error("未找到住院记录");
    }
  });
}

function getBedInfoByBedNumber(bedNumber) {
  console.log("拿到病床号")
  console.log(bedNumber)
  return listBed({bedNumber}).then(response => {
    if (response && response.rows && response.rows.length > 0) {
      return response.rows[0]; // 返回第一条匹配的病床信息
    } else {
      throw new Error("未找到对应的病床信息");
    }
  });
}

function updateBedStatus(bedId) {
  console.log("更新病床状态")
  console.log(bedId)
  const data = {
    bedId: bedId,
    bedStatus: 0 // 将 bed_status 修改为 0
  };
  return updateBed(data);
}

async function updateBedStatusByPatientId(patientId) {
  try {
    // 1. 查询最近的住院记录
    const latestRecord = await getLatestHospitalRecord(patientId);
    const bedNumber = latestRecord.bedNumber;

    // 2. 查询病床信息
    const bedInfo = await getBedInfoByBedNumber(bedNumber);

    console.log(bedInfo);
    const bedId = bedInfo.bedId;
    console.log("病床号")
    console.log(bedId);

    // 3. 修改病床状态
    await updateBedStatus(bedId);
    console.log("病床状态更新成功");
  } catch (error) {
    console.error("更新病床状态失败：", error);
  }
}

const employeeNameCache = ref({}); // 用于缓存员工姓名

function getEmployeeName(employeeId) {
  if (!employeeId) return '未知';

  // 如果缓存中已经有该员工的姓名，直接返回
  if (employeeNameCache.value[employeeId]) {
    return employeeNameCache.value[employeeId];
  }

  // 调用接口获取员工姓名
  getMEmoployee(employeeId).then(response => {
    console.log("患者id")
    // console.log(employeeId)
    // console.log(response);
    if (response && response.name) {
      employeeNameCache.value[employeeId] = response.name; // 缓存结果
      return response.name;
    } else {
      return '未知';
    }
  }).catch(err => {
    console.error("获取员工姓名失败：", err);
    return '未知';
  });

  return '加载中...'; // 在接口返回之前显示加载中
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patientId: null,
    dischargeDate: null,
    doctorId: null,
    dischargeDiagnosis: null,
    nurseId: null,
    dischargeAdvice: null,
    dischargeCondition: null,
    registrationId: null,
    ext1: null,
    ext2: null,
    ext3: null
  },
  rules: {},
});

const {queryParams, form, rules} = toRefs(data);

function handlePatientChange(patientId) {
  if (!patientId) return; // 如果没有选择患者，直接返回

  // 调用接口获取住院记录
  listBeinhospital2({patientId}).then(response => {
    // console.log("出院记录")
    // console.log(response)
    if (response && response.length > 0) {
      // 筛选出最新住院记录
      const latestHospitalRecord = response.reduce((latest, current) => {
        return new Date(current.admissionTime) > new Date(latest.admissionTime) ? current : latest;
      });

      // 提取 nurseId 和 doctorId 并赋值给表单
      form.value.nurseId = latestHospitalRecord.nurseId;
      form.value.doctorId = latestHospitalRecord.doctorId;
    } else {
      // 如果没有住院记录，清空 nurseId 和 doctorId
      form.value.nurseId = null;
      form.value.doctorId = null;
    }
  }).catch(err => {
    console.error("获取住院记录失败：", err);
    form.value.nurseId = null;
    form.value.doctorId = null;
  });
}

function getPatientName(patientId) {
  const patient = patientList.value.find(p => p.patientId === patientId);
  return patient ? patient.realName : '未知';
}




// aaa
async function getCorrespondingHospitalRecord(patientId, dischargeDate) {
  return listBeinhospital2({patientId}).then(response => {
    if (response && response.length > 0) {
      // 找到在出院日期之前的那次住院记录
      const correspondingRecord = response
          .filter(record => new Date(record.admissionTime) <= new Date(dischargeDate))
          .reduce((latest, current) => {
            return new Date(current.admissionTime) > new Date(latest.admissionTime) ? current : latest;
          });
      return correspondingRecord;
    } else {
      throw new Error("未找到对应的住院记录");
    }
  });
}


async function getList() {
  loading.value = true;
  listChuyuan(queryParams.value).then(async response => {
    chuyuanList.value = response.rows;
    total.value = response.total;
    loading.value = false;

    // 遍历 chuyuanList，获取医生和护士的姓名
    for (const record of chuyuanList.value) {
      // 获取与出院日期对应的住院记录
      const correspondingHospitalRecord = await getCorrespondingHospitalRecord(record.patientId, record.dischargeDate);
      if (correspondingHospitalRecord) {
        record.doctorId = correspondingHospitalRecord.doctorId;
        record.nurseId = correspondingHospitalRecord.nurseId;
        record.latestAdmissionDate = correspondingHospitalRecord.admissionTime;
      }

      // 获取医生和护士的姓名
      getEmployeeName(record.doctorId);
      getEmployeeName(record.nurseId);
    }
  });

  // 获取患者列表
  listjiuzhen().then(response => {
    patientList.value = response;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    dischargeRecordId: null,
    patientId: null,
    dischargeDate: null,
    doctorId: null,
    dischargeDiagnosis: null,
    nurseId: null,
    dischargeAdvice: null,
    dischargeCondition: null,
    registrationId: null,
    ext1: null,
    ext2: null,
    ext3: null
  };
  proxy.resetForm("chuyuanRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.dischargeRecordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加出院记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _dischargeRecordId = row.dischargeRecordId || ids.value
  getChuyuan(_dischargeRecordId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改出院记录";
  });
}

async function submitForm() {
  proxy.$refs["chuyuanRef"].validate(async valid => {
    if (valid) {
      try {
        // 获取与出院日期对应的住院记录
        const correspondingHospitalRecord = await getCorrespondingHospitalRecord(form.value.patientId, form.value.dischargeDate);
        if (correspondingHospitalRecord) {
          form.value.doctorId = correspondingHospitalRecord.doctorId;
          form.value.nurseId = correspondingHospitalRecord.nurseId;
        }

        // 提交出院记录
        if (form.value.dischargeRecordId != null) {
          await updateChuyuan(form.value);
          proxy.$modal.msgSuccess("修改成功");
        } else {
          await addChuyuan(form.value);
          proxy.$modal.msgSuccess("新增成功");
        }

        // 更新病床状态
        await updateBedStatusByPatientId(form.value.patientId);

        open.value = false;
        getList();
      } catch (error) {
        console.error("提交失败：", error);
        proxy.$modal.msgError("提交失败");
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _dischargeRecordIds = row.dischargeRecordId || ids.value;
  proxy.$modal.confirm('是否确认删除出院记录编号为"' + _dischargeRecordIds + '"的数据项？').then(function () {
    return delChuyuan(_dischargeRecordIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('nurse/chuyuan/export', {
    ...queryParams.value
  }, `chuyuan_${new Date().getTime()}.xlsx`)
}

getList();
</script>